import {
  cadAppLog,
  CMEVENTS,
  pickedFaceData,
  pickedLineData,
  pickedModelData,
} from '@amcax/base';
import { InputWithFormat } from '@app-cad/common/components/command-form/InputWithFormat';
import { docMgr, userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { Box, TextField } from '@mui/material';
import { Empty } from 'antd';
import { pickBy } from 'lodash';
import React, { useEffect, useState } from 'react';
import {
  isSimpleSelectedModels,
  SelectedModels,
} from '../utils/SelectedModels';
import * as filter from './assets/filter.json';
import './assets/style.scss';

export default function DefaultPropertyPanel(props?: any) {
  cadAppLog('DefaultPropertyPanel', props);
  // const [open, setOpen] = useState(false)
  const [dxid, setDxid] = useState('');
  const [objLabel, setObjLabel] = useState('');
  const [params, setParams] = useState({});
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [placement, setPlacement] = useState([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [color, setColor] = useState('#fff');

  useEffect(() => {
    userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: true, width: 300 });
    registerSelectionEvents();
    return () => {
      userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: false, width: 300 });
    };
  }, []);
  // useEffect(() => {
  //   ctx2.emit(EVENTS.RIGHT_PANEL_TOGGLE, open)
  // }, [open])

  const registerSelectionEvents = () => {
    // ctx2.on(EVENTS.DOCKER_BAR_CHANGED, (view: string) => {
    //   if (view === 'property') {
    //     console.log('open property')
    //     setOpen(true)
    //   } else {
    //     console.log('close property')
    //     setOpen(false)
    //   }
    // })

    userEvents.on(
      CMEVENTS.MODELS_SELECTED,
      (selectedModels: SelectedModels) => {
        if (isSimpleSelectedModels(selectedModels)) {
          setupData(selectedModels.values().next().value);
        } else {
          setupData(selectedModels.selectedModels.values().next().value);
        }
      },
    );
    userEvents.on(CMEVENTS.MODEL_SELECTED, (data: pickedModelData) => {
      setupData(data);
    });
    userEvents.on(CMEVENTS.MESH_SELECTED, (data: pickedFaceData) => {
      setupData(data);
    });
    userEvents.on(CMEVENTS.MESH_SELECTED, (data: pickedLineData) => {
      setupData(data);
    });
  };

  const setupData = (
    data: pickedModelData | pickedFaceData | pickedLineData,
  ) => {
    if (data && data.objInfo) {
      const dxid = data.objInfo.shape;
      const label = data.objInfo.label;
      const editableParams = pickBy(
        data.objInfo.params,
        (_, key) => filter[key]?.show,
      );
      const placement = data.objInfo.placement;
      setDxid(dxid);
      setObjLabel(label);
      setParams(editableParams);
      setPlacement(placement);
      setColor('#fff');
    } else {
      setDxid('');
      setObjLabel('');
      setParams({});
      setPlacement([]);
      setColor('#fff');
    }
  };

  const isNumber = (n: any): boolean => {
    return !isNaN(parseFloat(n)) && isFinite(n);
  };

  // ==== 修改图形参数 ====
  const handleParamsChange = (key: string, value: any) =>
    setParams({ ...params, [key]: value });

  const handleParamsCommit = async (key: string) => {
    if (dxid) {
      const value = params[key];
      if (!isNumber(value) && value != 0) {
        return;
      }
      await wsApi.setParams(dxid, { [key]: parseFloat(value) });
    }
  };
  // ==== 修改图形参数 ====

  // ==== 修改图形位置 ====
  // const handlePlacementChange = (i: number, j: number, value: any) => {
  //   const _placement = [...placement];
  //   _placement[i][j] = value;
  //   setPlacement(_placement);
  // };
  // const handlePlacementCommit = async () => {
  //   if (dxid) {
  //     if (
  //       isNumber(placement[0][0]) &&
  //       isNumber(placement[0][1]) &&
  //       isNumber(placement[0][2]) &&
  //       isNumber(placement[1][0]) &&
  //       isNumber(placement[1][1]) &&
  //       isNumber(placement[1][2]) &&
  //       isNumber(placement[2][0]) &&
  //       isNumber(placement[2][1]) &&
  //       isNumber(placement[2][2])
  //     ) {
  //       await wsApi.setPlacement(
  //         dxid,
  //         [
  //           parseFloat(placement[0][0]),
  //           parseFloat(placement[0][1]),
  //           parseFloat(placement[0][2]),
  //         ],
  //         [
  //           parseFloat(placement[1][0]),
  //           parseFloat(placement[1][1]),
  //           parseFloat(placement[1][2]),
  //         ],
  //         [
  //           parseFloat(placement[2][0]),
  //           parseFloat(placement[2][1]),
  //           parseFloat(placement[2][2]),
  //         ],
  //       );
  //     }
  //   }
  // };
  // ==== 修改图形位置 ====

  // ==== 修改图形标签 ====
  const handleLabelChange = (value: string) => {
    setObjLabel(value);
  };
  const handleLabelCommit = async () => {
    if (dxid) {
      await wsApi.setLabel(dxid, objLabel);
      await docMgr.updateDocumentObjects([dxid]);
    }
  };
  // ==== 修改图形标签 ====
  // ==== 修改图形颜色 ====
  // const handleColorChange = async (value: string) => {
  //   setColor(value);
  //   if (dxid) {
  //     await wsApi.setColor(dxid, value);
  //     // // 重新渲染图形 暂时直接前端渲染，不通过后端事件响应
  //     // changeModelMaterial(dxid, { color: value })
  //     // ctx2.viewer.requestRender()
  //   }
  // };
  // ==== 修改图形颜色 ====

  // if (!dxid) return (<></>)

  return (
    <>
      {dxid ? (
        <Box sx={{ mt: '10px', overflowY: 'auto', width: '100%' }}>
          <TextField
            sx={{ width: '100%' }}
            margin='normal'
            label='名称'
            value={objLabel}
            onChange={(e) => handleLabelChange(e.target.value)}
            onKeyUp={(e) => {
              if (e.key === 'Enter') {
                handleLabelCommit();
              }
            }}
            size='small'
          />
          {/*
          <FormControl variant="filled">
            <FormControlLabel
              sx={{ ml: 0 }}
              control={<ColorPicker color={color} onColorChange={handleColorChange} />}
              label="颜色"
              labelPlacement="start"
            />
          </FormControl>
          */}
          {params ? (
            Object.entries(params).map(([key, value]) => {
              const filterObj = filter[key];

              const { type, zh: label = key } = filterObj;

              return (
                <fieldset
                  key={key}
                  className='my-2 px-2 py-1'
                >
                  <legend className='text-sm'>{label}</legend>
                  <InputWithFormat
                    value={value as any}
                    inputType={type}
                    disableParameter={true}
                    onChange={(v) => handleParamsChange(key, v)}
                    onKeyUp={(e) => {
                      if (e.key === 'Enter') {
                        handleParamsCommit(key);
                      }
                    }}
                  />
                </fieldset>
              );
            })
          ) : (
            <></>
          )}
          {/* <FormGroup row sx={{ mt: '10px' }}>
            <TextField
              sx={{ width: '30%', mr: '5px' }}
              label="位置X"
              value={placement[ 0 ][ 0 ]}
              onChange={e => handlePlacementChange(0, 0, e.target.value)}
              onKeyUp={e => {
                if (e.key === 'Enter') {
                  handlePlacementCommit()
                }
              }}
              size="small"
            />
            <TextField
              sx={{ width: '30%', mr: '5px' }}
              label="位置Y"
              value={placement[ 0 ][ 1 ]}
              onChange={e => handlePlacementChange(0, 1, e.target.value)}
              onKeyUp={e => {
                if (e.key === 'Enter') {
                  handlePlacementCommit()
                }
              }}
              size="small"
            />
            <TextField
              sx={{ width: '30%', mr: '5px' }}
              label="位置Z"
              value={placement[ 0 ][ 2 ]}
              onChange={e => handlePlacementChange(0, 2, e.target.value)}
              onKeyUp={e => {
                if (e.key === 'Enter') {
                  handlePlacementCommit()
                }
              }}
              size="small"
            />
          </FormGroup> */}
        </Box>
      ) : (
        <Box
          sx={{
            mt: '20px',
            overflowY: 'auto',
            width: '250px',
            display: 'flex',
            justifyContent: 'center',
          }}
        >
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description='请选择模型'
          />
        </Box>
      )}
    </>
  );
}
